<!-- src/views/pages/VehicleManage.vue -->
<template>
  <div class="vehicle-manage">
    <!-- 顶栏 -->
    <TopBar />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 菜单 -->
      <MenuLine />

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="openAddDialog">添加车辆</el-button>
      </div>

      <!-- 车辆列表 -->
      <el-table :data="vehicleList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="vehicleId" label="车辆编号" />
        <el-table-column prop="brand" label="品牌" width="150" />
        <el-table-column prop="model" label="型号" width="150" />
        <el-table-column prop="licensePlate" label="车牌号" width="150" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            {{ statusMap[row.status] || row.status }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="250" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteVehicle(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="30%"
        @close="resetForm"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item
            v-for="field in vehicleFields"
            :key="field.key"
            :label="field.label"
            :prop="field.key"
          >
            <el-input
              v-if="field.type === 'text'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              :maxlength="field.maxLength"
            />
            <el-select
              v-else-if="field.type === 'select'"
              v-model="form[field.key]"
              :placeholder="field.placeholder"
              style="width: 100%"
            >
              <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { useVehicleStore, vehicleFields, type Vehicle } from '@/stores/vehicle';
import TopBar from '@/components/TopBar.vue';
import MenuLine from '@/components/MenuLine.vue';

// 车辆 store
const vehicleStore = useVehicleStore();
const vehicleList = ref(vehicleStore.vehicles);

// 状态选项
const statusOptions = ref([
  { value: '可用', label: '可用' },
  { value: '维修中', label: '维修中' },
  { value: '不可用', label: '不可用' },
]);
const statusMap = {
  AVAILABLE: '可用',
  维修中: '维修中',
  不可用: '不可用',
};

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加车辆');
const isEdit = ref(false);
const form = ref<Vehicle>({
  id: 0,
  vehicleId: '',
  brand: '',
  model: '',
  licensePlate: '',
  status: '',
  createTime: '',
});
const formRef = ref<FormInstance>();

// 表单校验规则
const rules = ref<FormRules>({
  vehicleId: [
    { required: true, message: '请输入车辆编号', trigger: 'blur' },
    { pattern: /^V\d{3}$/, message: '车辆编号格式为 V+3位数字（如 V001）', trigger: 'blur' },
  ],
  brand: [
    { required: true, message: '请输入品牌', trigger: 'blur' },
    { min: 1, max: 20, message: '品牌长度在 1 到 20 字符', trigger: 'blur' },
  ],
  model: [
    { required: true, message: '请输入型号', trigger: 'blur' },
    { min: 1, max: 20, message: '型号长度在 1 到 20 字符', trigger: 'blur' },
  ],
  licensePlate: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z0-9]{5}$/, message: '请输入有效车牌号（如 京A12345）', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
});

// 获取车辆列表
const fetchVehicles = async () => {
  try {
    const result = await vehicleStore.fetchVehicles();
    vehicleList.value = result;
  } catch (error) {
    ElMessage.error('获取车辆列表失败');
  }
};

// 打开添加弹窗
const openAddDialog = () => {
  isEdit.value = false;
  dialogTitle.value = '添加车辆';
  dialogVisible.value = true;
};

// 打开编辑弹窗
const openEditDialog = (row: Vehicle) => {
  isEdit.value = true;
  dialogTitle.value = '编辑车辆';
  form.value = { ...row };
  dialogVisible.value = true;
};

// 提交表单（添加或编辑）
const submitForm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await vehicleStore.updateVehicle(form.value);
          ElMessage.success('编辑车辆成功');
        } else {
          await vehicleStore.createVehicle({
            vehicleId: form.value.vehicleId,
            brand: form.value.brand,
            model: form.value.model,
            licensePlate: form.value.licensePlate,
            status: form.value.status,
          });
          ElMessage.success('添加车辆成功');
        }
        dialogVisible.value = false;
        fetchVehicles();
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑车辆失败' : '添加车辆失败');
      }
    }
  });
};

// 删除车辆
const deleteVehicle = async (id: number) => {
  ElMessageBox.confirm('确定删除该车辆吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await vehicleStore.deleteVehicle(id);
        ElMessage.success('删除车辆成功');
        fetchVehicles();
      } catch (error) {
        ElMessage.error('删除车辆失败');
      }
    })
    .catch(() => {
      ElMessage.info('取消删除');
    });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    id: 0,
    vehicleId: '',
    brand: '',
    model: '',
    licensePlate: '',
    status: '',
    createTime: '',
  };
};

// 初始化加载
onMounted(() => {
  fetchVehicles();
});
</script>

<style scoped>
.vehicle-manage {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px; /* 留出顶栏高度 */
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px; /* 底部留白 */
}

.operation-bar {
  margin: 20px 0;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>